package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/*
*  自定义的类型转换器
*   可以把字符串转成任意的枚举类型BaseEnum
*
* targetType: 目标类型(枚举类)
* */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
          return  new Converter<String, T>() {
              @Override
              public T convert(String source) {
                  for (T enumConstant : targetType.getEnumConstants()) {
                         if(enumConstant.getCode().equals(Integer.parseInt(source))){
                               return  enumConstant;
                         }

                  }
                throw  new IllegalArgumentException("source是非法的");
              }
          };

    }
}
